#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>//用于文件输入的

#define BUFFER_SIZE 4096
#define ECHO_PORT 9999

// //检测方法的函数,返回1说明方法是GET、HEAD、POST其中一种，否则返回0
// int is_valid_http_method(const char* method) {
//     return strcmp(method, "GET") == 0 || strcmp(method, "HEAD") == 0 || strcmp(method, "POST") == 0;
// }

// //检测一些细节的函数
// int is_valid_http_format(const char* msg) {
//     // 检查是否包含HTTP结束标记（空行）
//     if (strstr(msg, "\r\n\r\n") == NULL) return 0;
    
//     // 检查首行格式 METHOD URI HTTP/VERSION
//     char first_line[256];
//     sscanf(msg, "%255[^\r\n]", first_line);//提取第一行
    
//     //判断首行，如果不是3，则说明格式错误
//     char method[16], uri[256], version[16];//方法最多不超过8字节，预留16字节
//     if (sscanf(first_line, "%15s %255s %15s", method, uri, version) != 3)
//         return 0;
    
//     // 检查HTTP版本格式
//     if (strncmp(version, "HTTP/", 5) != 0) return 0;
    
//     return 1;
// }
//发送信息的函数
void send_request(int sock, const char *request) {
    send(sock, request, strlen(request), 0);
}

//接收信息
void receive_response(int sock) {
    char buffer[BUFFER_SIZE];
    ssize_t bytes_received;
    
    printf("Receiving response...\n");
    while ((bytes_received = recv(sock, buffer, sizeof(buffer) - 1, 0)) > 0) {
        buffer[bytes_received] = '\0';
        printf("%s", buffer);
    }
    if (bytes_received == 0) {
        printf("\nConnection closed by server\n");
    } else if (bytes_received < 0) {
        perror("recv failed");
    }
}

int main(int argc, char *argv[]) {
    if (argc < 3 || argc > 4) {
        fprintf(stderr, "Usage: %s <server-ip> <port> [file] \n", argv[0]);
        return EXIT_FAILURE;
    }

    int sock;
    struct sockaddr_in server_addr;
    char request[BUFFER_SIZE];
    
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        perror("Socket creation failed");
        return EXIT_FAILURE;
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[2]));
    if (inet_pton(AF_INET, argv[1], &server_addr.sin_addr) <= 0) {
        perror("Invalid address");
        close(sock);
        return EXIT_FAILURE;
    }

    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("Connection failed");
        close(sock);
        return EXIT_FAILURE;
    }

    printf("Connected to server %s:%s\n", argv[1], argv[2]);
    
    if (argc == 4) {
        int fd = open(argv[3], O_RDONLY);
        if (fd < 0) {
            perror("Open file failed");
            close(sock);
            return EXIT_FAILURE;
        }
        ssize_t n = read(fd, request, BUFFER_SIZE - 1);
        if (n < 0) {
            perror("Read file failed");//文件没打开
            close(fd);
            close(sock);
            return EXIT_FAILURE;
        }
        request[n] = '\0';
        close(fd);
    } else {
        printf("Enter HTTP request: \n");
        fgets(request, BUFFER_SIZE, stdin);
    }
    
    send_request(sock, request);
    receive_response(sock);
    close(sock);
    return EXIT_SUCCESS;
}